<template>
	<view class="message">
		<!--
		<common :tips='commonTips'></common>
		<u-mask z-index="1000" :custom-style="{background: 'rgba(0, 0, 0, 0.1)'}" :show="maskShow" @click="maskClick"></u-mask>
		<u-action-sheet :list="sessionLongpressList" @click="sessionLongpressAction" v-model="sessionLongpressShow"></u-action-sheet> -->
		<u-navbar :is-back='false' :title-bold='true' title-color="black" :border-bottom='false' title="消息"
			:is-fixed="true" :placeholder="true"> </u-navbar>
		<!-- 顶部搜索栏-start -->
		<view class="search">
			<view class="search-box">
				<u-search @search="search()" :show-action='false' v-model="keywords" class="search-box-u-search"
					placeholder="搜索好友、专业人士、职业、专家" :clearabled="true" :animation="true"></u-search>

				<!-- <view class="message-menu"> -->
				<!-- <u-icon name="scan" @click="scanCode" color="#646464" size="45"></u-icon> -->
				<!-- 		<navigator class="popup-menu-item" url="/sub/search/new-contact" open-type="navigate">
						<u-icon class="message-menu-icon" name="plus" :class="messageMenu.show ? 'im-bg-grey':''" color="#3f3f3f" size="40"></u-icon>
					</navigator> -->
				<!-- </view> -->

			</view>
		</view>

		<u-line length="92%" class="session-list-top-line" color="#F2F3F4" />
		<!-- 公众号 -->
		<!-- <official-account></official-account> -->
		<!-- 会话列表-start -->
		<view class="session-list">
			<navigator url="web">
				<session :item="gzh"></session>
			</navigator>
			<button open-type='contact' class="u-reset-button">
				<session :item="kf"></session>
			</button>
			<button style="color: red;" class="u-reset-button" @click.stop="equestSubscribeMessage">
<!-- 				<span @click="equestSubscribeMessage">订阅消息</span -->
				
				<session 
					 :item="dy"></session>
			</button>
			
			<button  class="u-reset-button" @click.stop="zanzhus">
<!-- 				<span @click="equestSubscribeMessage">订阅消息</span -->
				
				<session 
					 :item="zanzhu" ></session>
			</button>
			<block v-for="(item, index) in sessionListTop" :key="item.id">
				<session @click.native="goToSessionInfo(item.id, item.type, item.chat_id)"
					@longpress.native="sessionLongpress(item.id, item.top)" :item="item"></session>
			</block>
			<block v-for="(item, index) in sessionList" :key="item.id">
				<session @click.native="goToSessionInfo(item.id, item.type, item.chat_id)"
					@longpress.native="sessionLongpress(item.id, item.top)" :item="item"></session>
			</block>
			<!-- <view class="im-data-none" v-if="loadStatus" @click="onRefresh">{{loadStatus}}</view> -->
			<view class="im-data-none" v-if="loadStatus" @click="onRefresh">点击刷新</view>
		</view>
		<!-- 会话列表-end -->
		<!-- 跑马灯 -->
		<view class="notice">
<!-- 				<u-notice-bar v-if="show" color='#A1ADB0' bg-color='#ffffff' :volume-icon="false" :is-circular="true"
					:mode="list.length>1?'vertical':'horizontal'" :speed="0.1" :list="list" :close-icon="true"
					@close='close'></u-notice-bar> -->
			<u-notice-bar v-if="show" color='#A1ADB0' bg-color='#ffffff' :volume-icon="false" :is-circular="true"
				:mode="'horizontal'" :list="list" :close-icon="true"
				@close='close'></u-notice-bar>
			<view class="noticeShow" @click="show=true" v-else>
				<span>平台分享</span>
				<image src="../../static/img/lookgg.png" mode="widthFix"></image>
			</view>
		</view>

		<u-popup :closeable='true' :mask-close-able='true' border-radius='30' v-model="login" mode="bottom">
			<view class="sin u-row-center">
				<navigator class="btn" url="/pages/login/index">
					尚未登录，请先移步至登录页
					<uni-icons color='#fff' type="right" size='15'></uni-icons>
				</navigator>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		aroundNotice
	} from '../../api/index.js'
	export default {
		data() {
			return {
				kf: {
					avatar: "https://www.1glzx.com/img/avatar_customer.png",
					nickname: "客服(身份角色更改，请找客服.)",
					last_message: '',
					shield: false,
					top: "session-top",
					type: "single"
				},
				dy: {
					avatar: "https://www.1glzx.com/img/dingyuexiaoxi.png",
					nickname: "订阅消息",
					shield: false,
					top: "session-top",
					type: "single",
					last_message: '退出前按N次，可微信实时接收N条消息',
				},
				gzh: {
					avatar: "../../static/img/gzh.png",
					nickname: "3次回访半边莲",
					gzh: 1,
					last_message: '',
					shield: false,
					top: "session-top",
					type: "single"
				},
				zanzhu: {
					avatar: "../../static/svg/mine/sponser.svg",
					nickname: "民间感恩赞助",
					last_message: '',
					shield: false,
					top: "session-top",
					type: "single"
				},
				keywords: '',
				maskShow: false,
				messageMenu: {
					show: false
				},
				sessionList: [],
				sessionListTop: [],
				TODOcount: 0,
				pageDataLoadBool: false,
				isLogin: true,
				sessionLongpressList: [],
				sessionLongpressShow: false,
				loadStatus: '加载中...',
				commonTips: '',
				userInfo: '',
				list: [],
				show: true,
				login: false
			}
		},
		onLoad: function(e) {
			if (e.scene && this.isLogin) {
				this.ws.sid = e.scene
				this.ws.logout()
				this.isLogin=false;
			}
		},
		watch: {
			sessionList: {
				// 每个属性值发生变化就会调用这个函数
				handler(newVal, oldVal) {
					console.log('sessionList:', newVal)
				},
				// 立即处理 进入页面就触发
				immediate: true,
				// 深度监听 属性的变化
				deep: true
			}
		},
		onShow: function() {
			if (this.ws.getUserInfo()){
				uni.getSetting({
						withSubscriptions: true,
						success(res) {
							console.log( res, '订阅信息', res.subscriptionsSetting);
							if (!res.subscriptionsSetting.mainSwitch) {
								wx.requestSubscribeMessage({
								tmplIds: ['WqKIXxjw4lMOKBlWHXmiWefdVXzNKp8ZWidOMK7i8OQ'], // 这里填写你的模板ID
								success: (res) => {
									console.log('res','res')
									
								  if (res['WqKIXxjw4lMOKBlWHXmiWefdVXzNKp8ZWidOMK7i8OQ'] === 'accept') {
								    // 用户同意订阅
								    uni.showModal({
								      title: '提示',
								      content: '您已同意订阅消息，如重复订阅会相应增加1次接收次数',
								      showCancel: false
								    });
								  } else {
								    // 用户拒绝订阅
								    uni.showModal({
								      title: '提示',
								      content: '开启微信通知：“···”-设置-订阅消息-接收通知-新留言消息（接收）',
								      showCancel: false
								    });
								  }
								},
								fail: (err) => {
								  uni.showModal({
								    title: '提示',
								    content: '开启微信通知：“···”-设置-订阅消息-接收通知-新留言消息（接收）',
								    showCancel: false
								  });
								}
								});
							}
						},
					})
				
			}
			
			setTimeout(() => {
			    let user = this.ws.getUserInfo()
			    if (user) {
			      	this.login = false
			      	this.ws.pageRefresh.message = true
			      	this.ws.pageRefresh.sessionInfo = true
			      	this.ws.init(user.token, user.auth_token)
			      	if (!user.job) {
			      		uni.redirectTo({
			      			url: '/sub/center/choose-role'
			      		})
			      	}
			      } else {
			      	this.login = true
			      } 
				   this.init()
				   this.ws.pageFun(this.pageDataLoad, this);
				   if (this.ws.pageRefresh.message) {
				   	// 被其他页面通知刷新会话列表(更新列表中的好友备注等)
				   	this.ws.pageFun(this.pageDataLoad, this);
				   	this.ws.clearPageRefresh()
				   	this.ws.pageRefresh.message = false
				   	this.ws.pageRefresh.sessionInfo = false
				   	this.ws.messageShow = [] // 已经重载,无需执行messageShow中的方法
				   	return;
				   }
				   if (this.ws.messageShow.length) {
				   	for (let m in this.ws.messageShow) {
				   		if (typeof this.ws.messageShow[m] == 'function') {
				   			this.ws.messageShow[m](this)
				   			this.ws.messageShow[m] = null
				   		}
				   	}
				   }
				   if (!this.pageDataLoadBool) {
				   	return;
				   }
				   this.ws.checkNetwork(this)
				   this.ws.pageFun(function() {
				   	this.ws.send({
				   		c: 'ImBase',
				   		a: 'loadTODO',
				   		data: {
				   			'method': 'get-all-count'
				   		}
				   	})
				   }, this);
			}, 1600);
			
			
		},
		onPullDownRefresh: function() {


			let user = this.ws.getUserInfo()
			if (user) {
				this.login = false
				this.ws.pageRefresh.message = true
				this.ws.pageRefresh.sessionInfo = true
				this.ws.init(user.token, user.auth_token)
				if (!user.job) {
					uni.redirectTo({
						url: '/sub/center/choose-role'
					})
				}
			} else {
				this.login = true
			}

			this.ws.pageFun(this.pageDataLoad(true), this);
			var that = this
			that.init()

			if (this.ws.pageRefresh.message) {
				// 被其他页面通知刷新会话列表(更新列表中的好友备注等)
				this.ws.pageFun(this.pageDataLoad, this);
				this.ws.clearPageRefresh()
				this.ws.pageRefresh.message = false
				this.ws.pageRefresh.sessionInfo = false
				this.ws.messageShow = [] // 已经重载,无需执行messageShow中的方法
				return;
			}
			if (this.ws.messageShow.length) {
				for (let m in this.ws.messageShow) {
					if (typeof this.ws.messageShow[m] == 'function') {
						this.ws.messageShow[m](that)
						this.ws.messageShow[m] = null
					}
				}
			}
			if (!this.pageDataLoadBool) {
				return;
			}
			that.ws.checkNetwork(that)
			that.ws.pageFun(function() {
				that.ws.send({
					c: 'ImBase',
					a: 'loadTODO',
					data: {
						'method': 'get-all-count'
					}
				})
			}, that);
			this.ws.onMessageCallBack.set('load_session_list', (msg) => {
				if (msg.data.data.refresh && msg.data.data.method == 'load') {
					uni.showToast({
						title: '刷新成功~'
					})
					uni.stopPullDownRefresh()
				}
			})
		},
		methods: {
			onRefresh() {
			    let user = this.ws.getUserInfo()
			    if (user) {
			      	this.login = false
			      	this.ws.pageRefresh.message = true
			      	this.ws.pageRefresh.sessionInfo = true
			      	this.ws.init(user.token, user.auth_token)
			      	if (!user.job) {
			      		uni.redirectTo({
			      			url: '/sub/center/choose-role'
			      		})
			      	}
			    } else {
			      	this.login = true
			    } 
			   this.init()
			   this.ws.pageFun(this.pageDataLoad, this);
			   if (this.ws.pageRefresh.message) {
				// 被其他页面通知刷新会话列表(更新列表中的好友备注等)
				this.ws.pageFun(this.pageDataLoad, this);
				this.ws.clearPageRefresh()
				this.ws.pageRefresh.message = false
				this.ws.pageRefresh.sessionInfo = false
				this.ws.messageShow = [] // 已经重载,无需执行messageShow中的方法
				return;
			   }
			   if (this.ws.messageShow.length) {
				for (let m in this.ws.messageShow) {
					if (typeof this.ws.messageShow[m] == 'function') {
						this.ws.messageShow[m](this)
						this.ws.messageShow[m] = null
					}
				}
			   }
			   if (!this.pageDataLoadBool) {
				return;
			   }
			   this.ws.checkNetwork(this)
			   this.ws.pageFun(function() {
				this.ws.send({
					c: 'ImBase',
					a: 'loadTODO',
					data: {
						'method': 'get-all-count'
					}
				})
			   }, this);
			},
			zanzhus() {
				console.log('22')
				uni.navigateTo({
					url: '/pages/center/sponser'
				})
			},
			init() {
				aroundNotice().then(res => {
					if (res.code == 1) {
						this.list = res.data.list.map(obj => '平台分享：' + obj.content);
					}
				})
			},
			equestSubscribeMessage() {
				
				   // uni.requestSubscribeMessage({
				   //      tmplIds: ['WqKIXxjw4lMOKBlWHXmiWefdVXzNKp8ZWidOMK7i8OQ'],
				   //      success(res) {
							// 	this.subscribed = true;
								
				   //      },
				   //      fail(err) {
				   //      	  // 用户拒绝订阅该模板消息
							// 	this.subscribed = false;
				   //      },
				   //      complete() {
				   //        // 无论确定还是取消，只要点击按钮后都会执行
				   //      },
				   //    })

				// uni.openSetting({
				//   success: (res) => {
				// 	if (res.authSetting['scope.userNotification']) {
				// 	  console.log('用户已开启通知权限');
				// 	} else {
				// 	  console.log('用户未开启通知权限');
				// 	}
				//   },
				//   fail: (err) => {
				// 	console.error('拉起通知设置页面失败', err);
				//   }
				// }); 
				
				uni.getSetting({
						withSubscriptions: true,
						success(res) {
							console.log( res, '订阅信息', res.subscriptionsSetting);
							if (res.subscriptionsSetting.mainSwitch) {
								wx.requestSubscribeMessage({
								tmplIds: ['WqKIXxjw4lMOKBlWHXmiWefdVXzNKp8ZWidOMK7i8OQ'], // 这里填写你的模板ID
								success: (res) => {
									console.log('res','res')
									
								  if (res['WqKIXxjw4lMOKBlWHXmiWefdVXzNKp8ZWidOMK7i8OQ'] === 'accept') {
								    // 用户同意订阅
								    uni.showModal({
								      title: '提示',
								      content: '您已同意订阅消息，如重复订阅会相应增加1次接收次数',
								      showCancel: false
								    });
								  } else {
								    // 用户拒绝订阅
								    uni.showModal({
								      title: '提示',
								      content: '开启微信通知：“···”-设置-订阅消息-接收通知-新留言消息（接收）',
								      showCancel: false
								    });
								  }
								},
								fail: (err) => {
								  uni.showModal({
								    title: '提示',
								    content: '开启微信通知：“···”-设置-订阅消息-接收通知-新留言消息（接收）',
								    showCancel: false
								  });
								}
								});
							} else {
	
								uni.openSetting({
								  success: (res) => {
									if (res.authSetting['scope.userNotification']) {
									  console.log('用户已开启通知权限');
									} else {
									  console.log('用户未开启通知权限');
									}
								  },
								  fail: (err) => {
									console.error('拉起通知设置页面失败', err);
								  }
								});
							}
						},
					})


			  // wx.requestSubscribeMessage({
			  //   tmplIds: ['WqKIXxjw4lMOKBlWHXmiWefdVXzNKp8ZWidOMK7i8OQ'], // 这里填写你的模板ID
			  //   success: (res) => {
					// console.log('res','res')
					
			  //     if (res['WqKIXxjw4lMOKBlWHXmiWefdVXzNKp8ZWidOMK7i8OQ'] === 'accept') {
			  //       // 用户同意订阅
			  //       uni.showModal({
			  //         title: '提示',
			  //         content: '您已同意订阅消息，如重复订阅会相应增加1次接收次数',
			  //         showCancel: false
			  //       });
			  //     } else {
			  //       // 用户拒绝订阅
			  //       uni.showModal({
			  //         title: '提示',
			  //         content: '开启微信通知：“···”-设置-订阅消息-接收通知-新留言消息（接收）',
			  //         showCancel: false
			  //       });
			  //     }
			  //   },
			  //   fail: (err) => {
			  //     uni.showModal({
			  //       title: '提示',
			  //       content: '开启微信通知：“···”-设置-订阅消息-接收通知-新留言消息（接收）',
			  //       showCancel: false
			  //     });
			  //   }
			  // });
			},
			concern() {
				// 公众号
				wx.navigateToMiniProgram({
					appId: 'wxd31e74b41e3cd4fe',
					path: 'http://weixin.qq.com/r/UBI_JnTE_ymErTBF90dC',
					success(res) {
						console.log('跳转成功', res)
					},
					fail(res) {
						console.log('跳转失败', res)
					}
				})
			},
			close() {
				this.show = false
			},
			// 扫二维码
			scanCode() {
				let that = this
				uni.scanCode({
					success(res) {
						let url = res.path
						let sid = url.substring(url.indexOf('?') + 7, url.length);
						console.log(sid, '扫码');
						that.ws.sid = sid
						that.ws.logout();
					},
					fail(e) {
						console.log(e);
					}
				})
			},
			pageDataLoad: function(refresh = false) {
				this.pageDataLoadBool = true
				this.ws.send({
					c: 'User',
					a: 'loadSessionList',
					data: {
						'refresh': refresh
					}
				})
				this.ws.send({
					c: 'ImBase',
					a: 'loadTODO',
					data: {
						'method': 'get-all-count'
					}
				})
			},
			goToSessionInfo: function(id, type, chat_id) {

				var url = '/sub/session-info/session-info?id=' + id
				if (type == 'service') {
					if (chat_id != 3) {
						url = '/sub/session-info/notice-session-info?session_id=' + id
					}
				}
				uni.navigateTo({
					url: url
				})
			},
			sessionLongpress: function(id, top) {
				this.sessionLongpressShow = true
				this.sessionLongpressList = [{
					text: top ? '取消置顶' : '置顶',
					id: id
				}, {
					text: '移除会话',
					color: '#f74c31',
					id: id
				}]
			},
			sessionLongpressAction: function(idx) {
				var that = this
				if (idx == 0) {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								id: that.sessionLongpressList[idx].id,
								action: 'session-top',
								source: 'uni-app'
							}
						})
					}, that)
				} else if (idx == 1) {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								action: "session-remove",
								id: that.sessionLongpressList[idx].id,
								source: 'uni-app'
							}
						});
					}, that)
				}
			},
			maskClick: function() {
				this.messageMenu.show && this.toggleMessageMenu()
			},
			toggleMessageMenu: function(e) {
				var that = this
				if (that.messageMenu.show) {
					that.maskShow = false
					that.messageMenu.show = false
					return;
				}
				that.messageMenu = {
					show: true,
					top: (e.detail.y + 14) + 'px',
					left: (e.detail.x - 120) + 'px'
				}
				that.maskShow = true
			},
			search: function() {
				if (!this.keywords) {
					return;
				}
				uni.navigateTo({
					url: '/sub/search/search?keywords=' + this.keywords,
					success: () => {
						this.keywords = ''
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.sin {
		height: 30vh;
		display: flex;
		padding: 40rpx 0;

		.btn {
			border-radius: 30px;
		}
	}


	.notice {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		display: flex;
		justify-content: flex-end;

		.noticeShow {
			width: 165rpx;
			margin-right: 30rpx;
			margin-bottom: 30rpx;
			box-shadow: 0px 4px 8px 0px rgba(59, 129, 147, 0.1);
			border-radius: 30px;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 30px;
			width: 83px;
			padding: 10rpx;
			font-size: 12px;
			color: #A1ADB0;

			image {
				width: 9.5px;
				margin-left: 10rpx;
			}
		}

		u-notice-bar {
			width: 100vw;
		}
	}

	.message {
		background: #FFFFFF;
	}

	.search {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-box {
		display: flex;
		align-items: center;
		padding: 20rpx 0 10rpx 0;
	}

	.search-box {
		width: 100%;
		padding: 20rpx 30rpx;
	}

	.search-box-u-search {
		width: 100%;
	}

	.search-box .message-menu {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 20rpx;
	}

	.message-menu .message-menu-icon {
		padding: 6rpx;
		z-index: 1001;
		border-radius: 4px;
	}

	.message-menu-box {
		position: absolute;
		background: #FFFFFF;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, .1);
		border-radius: 4px;
		z-index: 1001;
	}

	.popup-menu .popup-menu-item {
		padding: 30rpx 70rpx;
		text-align: center;
		border-bottom: 1px solid #F3F4F6;
	}

	.popup-menu .popup-menu-item:last-child {
		border: none;
	}

	.to-do .to-do-cell-item .to-do-cell-item-icon {
		margin-right: 10rpx;
	}

	.session-list-top-line {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.im-bg-grey {
		background-color: $--grey;
		color: $--white;
	}
</style>